package org.study.mongo.api.util;

import com.mongodb.*;
import com.mongodb.client.*;
import lombok.experimental.UtilityClass;
import org.bson.Document;

import java.util.Objects;

/**
 * MongoDb 工具类
 *
 * @author doveylovey
 * @date 2020年06月02日
 */
@UtilityClass
public class MongoDbUtils {
    public final String HOST = "127.0.0.1";
    public final int PORT = 27017;
    public final String USERNAME = "root";
    public final String PASSWORD = "root";
    public final String DB_NAME = "test";
    public final String COLLECTION_NAME = "col_test";

    /**
     * 连接地址为 localhost，端口为 27017 的 MongoDB 服务
     */
    public MongoClient getMongoClient() {
        // 默认连接地址为 localhost，端口为 27017
        return MongoClients.create();
    }

    /**
     * 连接地址为 localhost，端口为 27017 的 MongoDB 服务
     *
     * @param username 用户名
     * @param password 密码
     * @param dbName   数据库名称
     */
    public MongoClient getMongoClient(String username, String password, String dbName) {
        MongoClientSettings settings = MongoClientSettings.builder()
                .credential(MongoCredential.createCredential(username, dbName, password.toCharArray()))
                .build();
        return MongoClients.create(settings);
    }

    /**
     * 通过 URI 连接 MongoDB 服务
     *
     * @param host     地址
     * @param port     端口
     * @param username 用户名
     * @param password 密码
     * @param dbName   数据库名称
     */
    public MongoClient getMongoClient(String host, Integer port, String username, String password, String dbName) {
        // mongodb://[username:password@]host1[:port1][,host2[:port2],…[,hostN[:portN]]][/[database][?options]]
        String connectionString = String.format("mongodb://%s:%s@%s:%d/%s", username, password, host, port, dbName);
        // return MongoClients.create(connectionString);
        return MongoClients.create(new ConnectionString(connectionString));
    }

    public MongoDatabase getDatabase(String dbName) {
        // 获取MongoClient
        MongoClient client = getMongoClient(HOST, PORT, USERNAME, PASSWORD, dbName);
        // 获取数据库对象
        MongoDatabase mongoDatabase = client.getDatabase(dbName);
        return mongoDatabase;
    }

    public MongoCollection<Document> getCollection(String dbName, String collectionName) {
        // 获取数据库对象
        MongoDatabase mongoDatabase = getDatabase(dbName);
        // 获取数据表对象
        MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(collectionName);
        return mongoCollection;
    }

    /**
     * 关闭 MongoClient 连接
     *
     * @param mongoClient
     * @return void
     */
    public void closeMongoClient(MongoClient mongoClient) {
        if (Objects.nonNull(mongoClient)) {
            mongoClient.close();
        }
    }
}
